package com.verify.resp;

import com.verify.util.JariJson;
import com.verify.util.R;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 实现接口响应统一处理
 *
 * @author Justyn
 * @date 2022/11/14 17:30
 */
@RestControllerAdvice
public class CommonResponseAdvice implements ResponseBodyAdvice<Object> {

    @SuppressWarnings("all")
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        ResponseAdvice respMethood = methodParameter.getMethodAnnotation(ResponseAdvice.class);
        ResponseAdvice respContrain = methodParameter.getContainingClass().getAnnotation(ResponseAdvice.class);
        if (respMethood == null && respContrain == null) {
            return false;
        }
        if (respMethood != null) {
            return respMethood.value();
        }
        return respContrain.value();
    }

    @SuppressWarnings("all")
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter,
                                  MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof R) {
            return o;
        }
        if (o instanceof String) {
            return JariJson.obj2str(R.ok().put("data", o));
        }
        return R.ok().put("data", o);
    }
}
